package com.guqj.nio.netty.pstack.client;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import com.guqj.nio.netty.pstack.pojo.Header;
import com.guqj.nio.netty.pstack.pojo.MessageType;
import com.guqj.nio.netty.pstack.pojo.NettyMessage;

/**
 * 握手请求-客户端
 * 
 * @author guqj
 * @date 2016年11月25日
 */
public class LoginAuthReqHandler extends ChannelHandlerAdapter {

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		NettyMessage msg = new NettyMessage();
		Header header = new Header();
		header.setType(MessageType.LOGIN_REQ.value()); // 发送握手请求
		msg.setHeader(header);
		System.out.println("Client send Login Auth message: " + msg);
		ctx.writeAndFlush(msg);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		NettyMessage message = (NettyMessage) msg;
		if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
			byte loginResult = (byte) message.getBody();
			if (loginResult == (byte) 0) {
				ctx.close(); // 握手失败，关闭连接
			} else {
				System.out.println("Login is OK :" + message);
			}
		} else {
			ctx.fireChannelRead(msg);
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.fireExceptionCaught(cause);
	}
}
